import VueRouter from 'vue-router'
import Login from '../views/Login'
import Home from '../views/Home'
import Guide from '../pages/HomeModule/Guide'
import RoomList from '../pages/HomeModule/RoomList'
import Room from '../pages/HomeModule/Room'
import Primary from '../views/Primary'
import Register from '../views/Register'
import QuestionList from '../pages/HomeModule/QuestionList'
import Question from '../pages/HomeModule/Question'
import axios from 'axios'
const router=new VueRouter({
	routes:[
	{
		name:'primary',
		path:'/',
		component:Primary,
	},
	{
		name:'login',
		path:'/login',
		component:Login
	},
	{
		name:'register',
		path:'/register',
		component:Register
	},
	{
		name:'home',
		path:'/home',
		component:Home,
		children:[
		{
			path:'',
			component:Guide,
		},
		{
			name:'guide',
			path:'guide',
			component:Guide
		},
		{
			name:'roomList',
			path:'roomList',
			component:RoomList,
		},
		{
			name:'room',
			path:'room',
			component:Room,
		},
		{
			name:'questionlist',
			path:'questionlist',
			component:QuestionList,
		},
		{
			name:'question',
			path:'question',
			component:Question
		}
		]
	},
	
	]
})
//全局前置路由守卫

router.beforeEach((to,from,next)=>{
	//是否是去首页或login页面
	if(to.path!=="/"&&to.path!=="/login"&&to.path!=="/register"){
		//不是,查询当前是否有token
		if(localStorage.getItem("token")){
		axios({
			method:'POST',
			url:'user/me',
			headers:{
				authorization:localStorage.getItem("token")
			}
		}).then(
			response=>{
				if(response.data.success){
					next()
				}else{
					next('login')
					alert("请先登录才能访问")
				}
				},
				error=>{
					next('login')
					alert("请先登录才能访问")
				}
		)
		}else{
			next('login')
			alert("请先登录才能访问")
		}
		
		
	}else{
			//首页 和 login页面放行
			next()
	}
	
})

export default router
